package com.example.pro1.service.zhao.kdniao.impl;

import com.example.pro1.config.zhao.LogisticsConfig;
import com.example.pro1.enums.OrderStatus;
import com.example.pro1.service.zhao.kdniao.KdniaoService;
import com.example.pro1.service.zhao.table.OrderInfoService;
import com.example.pro1.util.zhao.DateUtils;
import com.example.pro1.util.zhao.KdnioaSignUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.swing.text.html.parser.Entity;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class KdniaoServiceImpl implements KdniaoService {

    @Resource
    private LogisticsConfig logisticsConfig;
    @Resource
    private OrderInfoService orderInfoService;

    //发送订阅请求
    @Override
    public  Integer sendPost(Map<String,String> params) throws Exception {

        CloseableHttpClient closeableHttpClient= HttpClients.createDefault() ;//会话
        String callback=params.get("callback");
        String shipperCode=params.get("shipperCode");
        String LogisticCode=params.get("LogisticCode");//获取参数

        HttpPost httpPost = new HttpPost(logisticsConfig.getReqUrl());//产生Pos请求
        httpPost.setEntity(orderOnlineByJson(callback,shipperCode,LogisticCode));//设置请求体（orderOnlin已经Utf-8编码过了）
        httpPost.setHeader("Accept", "application/json");//设置请求头
        CloseableHttpResponse respose = closeableHttpClient.execute(httpPost);//获取返回

        try {
            Gson gson = new Gson();
            String x= EntityUtils.toString(respose.getEntity());
            log.info("-------",x);
            Map<String,Object> e=gson.fromJson(x,HashMap.class);
            if(e.get("Success").toString().equals("true"))
            {
                log.info("订阅成功");
                return 1;
            }
            else
            {
                log.info("订阅失败");
                return 0;
            }

        }
        finally{
            orderInfoService.updateOrderInfo(params.get("doerno"), OrderStatus.REFUND_SEND);//更新状态为已发货
            respose.close();
        }

    }

    //系统级返回体狗制造函数
    public Map<String,String> creatSys(Map<String ,Object> RequestData,String RequestType,String DataType) throws Exception {
        Gson gson = new Gson();
        Map<String,String> params = new HashMap();
        params.put("RequestData", URLEncoder.encode(gson.toJson(RequestData), "UTF-8"));//傻逼接口
        params.put("EBusinessID", logisticsConfig.getEBusinessID());
        params.put("RequestType", RequestType);//免费订阅接口指令1008/在途监控订阅接口指令8008/地图版订阅接口指令8005
        String dataSign=KdnioaSignUtils.encrypt(gson.toJson(RequestData), logisticsConfig.getApiKey());
        log.info("签名==>{}",dataSign);
        params.put("DataSign", dataSign);
        params.put("DataType", URLEncoder.encode(DataType,"UTF-8"));//傻逼接口


        return params;
    }

   /* RequestData String 是 请求内容为 com.alibaba.fastjson.JSON 格式EBusinessID String 是 用户 ID
    RequestType String 是 请求接口指令DataSign String 是 数据内容签名DataType String 是
            DataType=2，请求、返回数据类型均为 JSON 格式*/

    //为请求生成请求体
    public StringEntity orderOnlineByJson(String callback,String shipperCode,String LogisticCode) throws Exception {

        //把(jsonStr+APIKey)进行MD5加密，然后Base64编码，最后 进行URL(utf-8)编码
        Map<String ,Object> RequestData=new HashMap<>();
        RequestData.put("Callback",callback);
        RequestData.put("ShipperCode",shipperCode);//快递公司编号
        RequestData.put("LogisticCode",LogisticCode);//快递单号
        RequestData.put("PayType","1");//快递单号

        Map<String ,String> Sender=new HashMap<>();
        Sender.put("Name","1255760");//ceshi
        Sender.put("Mobile","13700000000");//ceshi
        Sender.put("ProvinceName","广东省");//ceshi
        Sender.put("CityName","深圳市");//ceshi
        Sender.put("ExpAreaName","福田区");//ceshi
        Sender.put("Address","测试地址");//ceshi
        RequestData.put("Sender",Sender);
        Map<String ,String> Receiver=new HashMap<>();
        Receiver.put("Name","1255760");//ceshi
        Receiver.put("Mobile","13800000123");//ceshi
        Receiver.put("ProvinceName","广东省");//ceshi
        Receiver.put("CityName","深圳市");//ceshi
        Receiver.put("ExpAreaName","龙华新区");//ceshi
        Receiver.put("Address","测试地址2");//ceshi
        RequestData.put("Receiver",Receiver);

        List<Map<String,String>> Commodity=new ArrayList<>();
        HashMap x=new HashMap<String,String>();
        x.put("Name","书本");
        Commodity.add(x);
        RequestData.put("Commodity",Commodity);


        /*
        * CustomerName String(50) 可选ShipperCode 为SF时必填，对应寄件人/收件人手机号后四位；ShipperCode 为其他快递时，可不填或保留字段，不可传值*/
        RequestData.put("CustomerName",null);


        //获取系统级响应值
        Map<String, String> params = creatSys(RequestData, "1008", "2");

        // 以form表单形式提交post请求，post请求体中包含了应用级参数和系统级参数
        Gson gson = new Gson();
        List<NameValuePair> nvps = new ArrayList<>();
        for (String key : params.keySet()) {
            nvps.add(new BasicNameValuePair(key, (String) params.get(key)));
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps,"utf-8");//真他妈傻逼的垃圾接口
        return  entity;

    }



    /*
    { "EBusinessID": "1237100", "UpdateTime": "2015-03-11 16:26:11", "Success": true, "Reason": ""}*/
    public String creatSysR() throws UnsupportedEncodingException {

         Map<String,Object> params = new HashMap();


         params.put("EBusinessID", logisticsConfig.getEBusinessID());
         //2022-01-06 11:18:20

         params.put("Success", "true");
         params.put("Reason", "");
         params.put("UpdateTime", DateUtils.miao());

         List<NameValuePair> nvps = new ArrayList<>();
         for (String key : params.keySet()) {
             nvps.add(new BasicNameValuePair(key, (String) params.get(key)));
         }

         /*StringEntity entity = new UrlEncodedFormEntity(nvps,"utf-8");//真他妈傻逼的垃圾接口
         log.info(String.valueOf(entity));*/
         return new Gson().toJson(params);

     }








}
